package com.vincent.template.store;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CreateCache;
import com.vincent.template.commons.base.VctPair;
import com.vincent.template.service.security.UserRoleAuthService;
import com.vincent.template.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Vincent Wang
 * @date 2021/1/18 14:30
 */
@Component
public class UserRoleAuthStore {

    @Autowired
    private UserRoleAuthService userRoleAuthService;

    @CreateCache(name = "system:user:roleauth:")
    private Cache<String, VctPair<List<String>, List<String>>> roleAuthCache;

    public VctPair<List<String>, List<String>> findRolesAndAuths(String userId) {
        VctPair<List<String>, List<String>> rolesAndAuths = roleAuthCache.get(userId);
        if (rolesAndAuths != null) {
            return rolesAndAuths;
        }
        return refreshRolesAndAuths(userId);
    }

    public VctPair<List<String>, List<String>> refreshRolesAndAuths(String userId) {
        VctPair<List<String>, List<String>> rolesAndAuths = userRoleAuthService.findRolesAndAuths(userId);
        roleAuthCache.put(userId, rolesAndAuths,
                DateUtil.getMillisBetweenNowAndEndOfToday(), TimeUnit.MILLISECONDS);
        return rolesAndAuths;
    }
}
